<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use session;

/**
 *
 * 验证码生成及上传文件处理类
 * @author chenxiaodong <[<229168653@qq.com>]>
 */
class CommonApi extends Controller
{

  //生成验证码
  public function buildCode(Request $request)
  {
    $builder = new CaptchaBuilder;
    $builder->build();

    //获取验证码内容
    $phrase = $builder->getPhrase();
    //将验证码存到session
     // $request->session()->put('code', $phrase);
     $request->session()->flash('code', $phrase);
    //  \Session::save();
    //生成图片
    header("Cache-Control: no-cache, must-revalidate");
    header('Content-Type: image/jpeg');
    $builder->output();
    
    // exit;
  }
  

  /**
   * 验证码验证
   * @author chenxiaodong <[<229168653@qq.com>]>
   */
  public  static function CheckCode (Request $request, $formCodeName = 'code')
  {
       $userCode = $request->input($formCodeName);
       if ( $request->session()->get('code') == $userCode ) {
           return	true;
       }
       return false;
  }


  public function json($code, $msg, $data = [])
  {
    return response()->json([
      'status' => $code,
      'msg'    => $msg,
      'data'  => $data,
    ]);
  }

  //文件上传
  public function upload(
    Request $request,
    $formFileName = 'img',
    $allowExt = ['jpg', 'png', 'gif', 'jpeg']
  )
  {

      if (!$request->hasFile($formFileName)) {

        return $this->json(1404, '文件不存在');
      }

      //获取到文件的扩展名
      $extension = $request->$formFileName->extension();

      //判断扩展是不是允许上传的类型
      if (!in_array($extension, $allowExt)) {

          return $this->json(1401, '上传文件类型错误');
      }

      $fileName = $request->$formFileName->store('image');

      // return $this->json(1200, '文件上传成功', ['path' => $fileName]);
      return $fileName;
      // dd($extension);
  }

}
